<template>
  <div class="set-tag-layout hor-layout">
    <!--  内容布局  -->
    <!--    左边的标签树    -->
    <el-card class="lef-box-layout">
      <template #header>
        <div class="hor-layout-center-all box-card-title">
          项目文件夹标签树
          <div class="box-card-right-buttons">
            <el-button type="primary" size="small" @click="importPathData">导入</el-button>
            <el-button type="info" size="small" @click="exportPathData">导出</el-button>
          </div>
        </div>
      </template>
      <div class="ver-layout">
        <!--   标签树   -->
        <el-tree
          class="flag-tree-view"
          default-expand-all
          highlight-current
          check-strictly
          check-on-click-node
          node-key="id"
          :data="pageData.treeData"
          :props="pageData.defaultProps"
          @node-click="treeNodeClick"
        >
          <template #default="{ node, data }">
            <el-button
              type="primary"
              size="small"
              v-if="data.flag == 'addFirstLevelBtn'"
              @click.stop="addTreeData({}, { id: 'add_root_child_id' })"
              >新增一级标签
            </el-button>
            <div v-else class="custom-tree-node hor-layout-center">
              <span
                class="tree-node-label"
                :class="{
                  'tree-node-label-project': data.linkProject && data.linkProject.length
                }"
              >
                {{ node.label }}
              </span>
              <el-button
                link
                type="danger"
                v-if="node.label"
                icon="DeleteFilled"
                class="remove-icon-view"
                @click.stop="deleteTreeData(node, data)"
              ></el-button>
              <el-button
                link
                type="primary"
                icon="CirclePlusFilled"
                class="add-icon-view"
                @click.stop="addTreeData(node, data)"
              ></el-button>
            </div>
          </template>
        </el-tree>
      </div>
    </el-card>

    <!--   右边的操作布局   -->
    <el-card class="right-box-layout ver-layout">
      <template #header>
        <div v-if="pageData.currentNode" class="hor-layout-side-center">
          {{ pageData.currentNode.type == 'modify' ? '修改标签' : '新增标签' }}
        </div>
      </template>
      <!--    新增、修改标签    -->
      <div v-if="pageData.currentNode" class="add-flag-layout ver-layout">
        <div class="add-flag-item hor-layout-center">
          <div class="flag-path-view">标签路径:</div>
          <div class="flag-path-view flag-path-value-view">
            {{ pageData.currentNodeLabelStr }}
          </div>
        </div>
        <div class="add-flag-item hor-layout-center">
          <div class="flag-path-view">标签名称:</div>
          <el-input
            clearable
            size="small"
            style="width: 150px"
            placeholder="请输入标签名称"
            v-model="pageData.inputValue"
            @keyup.enter="newProjectFlag"
          ></el-input>
        </div>
        <!--      关联项目配置      -->
        <div class="link-project-layout ver-layout">
          <!--      关联项目        -->
          <div
            v-if="!pageData.currentNode.children || !pageData.currentNode.children.length"
            class="add-flag-item add-link-item hor-layout-center"
          >
            <div class="flag-path-view">关联项目:</div>
            <el-button
              icon="Link"
              size="small"
              type="warning"
              class="link-icon-view"
              @click.stop="addTreeFlagLink(node, data)"
              v-if="!pageData.currentNode.linkProject || !pageData.currentNode.linkProject.length"
              >选择
            </el-button>
            <el-tag
              class="custom-tree-link-tag"
              round
              closable
              size="small"
              :key="project.id"
              @click="addTreeFlagLink(node, data)"
              @close="removeLinkProject(project, node, data)"
              v-for="(project, projectIdx) in pageData.currentNode.linkProject"
            >
              {{ project.label }}
            </el-tag>
          </div>

          <!--      项目配置      -->
          <!--              <env-config-view></env-config-view>-->
        </div>
        <div class="hor-layout-center-all" style="margin-top: 10px">
          <el-button
            v-reclick
            size="medium"
            @click="newProjectFlag"
            :type="pageData.currentNode.type == 'modify' ? 'success' : 'primary'"
          >
            保存
          </el-button>
        </div>
      </div>
    </el-card>
    <!--  选择项目  -->
    <!--  选择项目  -->
    <!--  选择项目  -->
    <select-project-dialog
      ref="selectProjectRef"
      @confirmSelectProject="confirmSelectProject"
    ></select-project-dialog>
  </div>
</template>

<script setup lang="ts">
import { ElMessageBox, ElTree } from 'element-plus'
import { onMounted, reactive, ref } from 'vue'
import { managePlugin } from '../../../plugins/managePlugin'
import SelectProjectDialog from '../../../components/select-project-dialog.vue'
import { getNextChildNumberStr, getNextNumberStr, showToast } from '../../../utils/utils'

const selectProjectRef = ref<null>()

const pageData = reactive({
  defaultProps: {
    id: 'id',
    label: 'label',
    linkProject: 'linkProject'
  },
  inputValue: '',
  treeData: [],
  currentNode: { id: 'add_root_child_id' },
  currentNodeLabelStr: ''
})

//导入项目配置数据
const importPathData = async () => {
  await ElMessageBox.confirm(`导入后原有数据会被覆盖？`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
  let { result, message } = await managePlugin.importManageDataRender({ projectFlagStr: true })
  await showToast(message, result ? 'success' : 'error')
  if (result) await refreshTreeData()
}

//导出项目配置数据
const exportPathData = async () => {
  let { result, message } = await managePlugin.exportManageDataRender({ projectFlagStr: true })
  await showToast(message, result ? 'success' : 'error')
}

//
const getNextItem = (list, children) => {
  children.forEach((item) => {
    let { id, label } = item
    list.push({ id, label })
    if (item.children) getNextItem(list, item.children)
  })
}

//tree转换成文本
const getCurrentNodeLabelStr = (noSelf = false) => {
  let currentNodeList = []
  getNextItem(currentNodeList, pageData.treeData)
  pageData.currentNodeLabelStr =
    pageData.currentNode.id !== 'add_root_child_id'
      ? getNodeLabelStr(currentNodeList, noSelf)
      : ' / '
}

//获取项目路径
const getNodeLabelStr = (currentNodeList, noSelf) => {
  let nodePathStr = pageData.currentNode.id
    .split('_')
    .reduce((prev, cur, index, arr) => {
      let perItem = prev.length ? prev[prev.length - 1] : ''
      let curItem = perItem ? `${perItem}_${cur}` : cur
      return [...prev, curItem]
    }, [])
    .filter((item, index) => (noSelf ? item != pageData.currentNode.id : item))
    .map((id) => currentNodeList.find((item) => item.id === id).label)
    .join(' / ')
  return nodePathStr ? `${nodePathStr} /` : ' / '
}

//生成项目标签树的id
const generateProjectId = () => {
  if (pageData.currentNode.id == 'add_root_child_id') {
    let { id } = pageData.treeData[pageData.treeData.length - 1]
    return getNextNumberStr(id == 'add_root_child_id' ? '0' : id)
  } else {
    let currentNodeChildren = pageData.currentNode.children
    let currentNodeLastChild =
      currentNodeChildren && currentNodeChildren[currentNodeChildren.length - 1]
    return getNextChildNumberStr(
      currentNodeLastChild ? currentNodeLastChild.id : `${pageData.currentNode.id}_0`
    )
  }
}

//新增/修改保存
const newProjectFlag = async () => {
  if (!pageData.inputValue) return
  let projectFlagId = generateProjectId()
  const newChild = {
    id: projectFlagId,
    value: projectFlagId,
    label: pageData.inputValue
  }
  console.log('pageData.currentNode', pageData.currentNode)
  //主节点添加数据
  if (!pageData.currentNode || pageData.currentNode.id == 'add_root_child_id') {
    pageData.treeData.push(newChild)
    await saveProjectDataInCache('新增成功！')
  } else {
    if (pageData.currentNode.type == 'modify') {
      pageData.currentNode.label = pageData.inputValue
      pageData.currentNode.value = pageData.inputValue
      await saveProjectDataInCache('修改成功！')
    } else {
      if (!pageData.currentNode.children) {
        pageData.currentNode.children = []
      }
      pageData.currentNode.children.push(newChild)
      await saveProjectDataInCache('新增成功！')
    }
  }
  pageData.inputValue = ''
}

//保存数据到本地缓存中
const saveProjectDataInCache = async (toastMsg) => {
  await managePlugin.saveProjectFlagRender(JSON.stringify(pageData.treeData))
  if (toastMsg) await showToast(toastMsg)
}

//tree节点点击事件
const treeNodeClick = (data, node) => {
  data.type = 'modify'
  pageData.currentNode = data
  pageData.inputValue = data.label
  getCurrentNodeLabelStr(true)
}

//添加子节点
const addTreeData = (node, data) => {
  data.type = 'add'
  pageData.currentNode = data
  pageData.inputValue = ''
  getCurrentNodeLabelStr()
}

//添加树节点的关联项
const addTreeFlagLink = (node, data) => {
  selectProjectRef.value.showDialog(pageData.currentNode.linkProject)
}

//删除树的数据
const nextChildDelete = (children, mId) => {
  console.log('nextChildDelete', children)
  let index = children.findIndex((child) => child.id === mId)
  if (index > -1) children.splice(index, 1)
  else children.forEach((child) => child.children && nextChildDelete(child.children, mId))
}

//删除子节点
const deleteTreeData = async (node, data) => {
  await ElMessageBox.confirm(`确认删除标签【${node.label}】？`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
  nextChildDelete(pageData.treeData, data.id)
  await saveProjectDataInCache('删除成功！')
}

//确认选择项目路径标签
const confirmSelectProject = (linkProject) => {
  pageData.currentNode.linkProject = linkProject
  console.log('pageData.currentNode.linkProject', pageData.currentNode.linkProject)
}

//删除项目路径的标签
const removeLinkProject = (project, node, data) => {
  pageData.currentNode = data
  pageData.currentNode.linkProject.splice(
    pageData.currentNode.linkProject.findIndex((linkItem) => linkItem.id == project.id),
    1
  )
}

//刷新标签树数据
const refreshTreeData = async () => {
  pageData.treeData = await managePlugin.getProjectFlagRender()
  //进入页面判断缓存数据里面有没有addFirstLevelBtn这条数据，如果没有的话则手动添加一条
  if (!pageData.treeData.find((item) => item.flag == 'addFirstLevelBtn'))
    pageData.treeData.unshift({ flag: 'addFirstLevelBtn' })
}

//页面渲染时
onMounted(async () => {
  await refreshTreeData()
})
</script>

<style scoped lang="less">
.set-tag-layout {
  margin-left: 10px;
  width: calc(100% - 10px);
  height: 75vh;

  /deep/ .lef-box-layout > .el-card__header {
    padding: 10px;
  }

  /deep/ .right-box-layout > .el-card__header {
    padding: 10px;
    font-size: 14px;
  }

  .lef-box-layout {
    width: 50%;

    .box-card-title {
      position: relative;
      font-size: 14px;

      .box-card-right-buttons {
        position: absolute;
        right: 20px;
      }
    }

    //标签树
    .flag-tree-view {
      padding: 5px;
      height: 60vh;
      overflow-y: auto;
      border: 1px solid #ededed;

      .custom-tree-node {
        flex: 1;
        display: flex;
        font-size: 13px;
        padding-right: 8px;
        border-bottom: 1px solid #ededed;

        .tree-node-label {
          color: #333;
        }

        .tree-node-label-project {
          color: #409eff;
        }
      }

      .link-icon-view {
        margin-left: 8px;
      }

      .remove-icon-view {
        margin-left: 5px;
      }

      .add-icon-view {
        margin-left: 5px;
      }
    }
  }

  .right-box-layout {
    width: 50%;
    height: 75vh;
    margin-left: 10px;
    padding-left: 10px;

    //添加标签布局
    .add-flag-layout {
      .add-flag-item {
        margin-bottom: 11px;
        font-size: 14px;
        color: #000000;

        .flag-path-view {
          margin-right: 15px;
        }

        .flag-path-value-view {
          border-bottom: 1px solid #e0e3e9;
          font-size: 13px;
          color: #999999;
        }

        .add-env-title {
          flex-shrink: 0;

          .flag-model-btn {
            margin: 0 auto;
            margin-top: 10px;
            width: fit-content;
          }
        }

        .flag-path-input-view {
          width: 100%;
        }

        .save-flag-btn {
          margin-left: 10px;
        }
      }

      .add-flag-item.add-link-item {
        padding-top: 10px;
        border-top: 1px solid #eaeaea;

        .custom-tree-link-tag {
          margin-right: 8px;
        }
      }

      .add-flag-item.add-env-item {
        margin-top: 10px;
      }
    }
  }
}
</style>
